Android SharedPreferences Example 您所在的位置:网站首页 android sharedpreferences 权限 Android SharedPreferences Example

Android SharedPreferences Example

#Android SharedPreferences Example| 来源: 网络整理| 查看: 265

Here you will get android SharedPreferences example.

SharedPreferences in android is used to save data which is available across entire application and the data persists even after the application is closed. It is widely used for session management in android applications. SharedPreferences uses key-value pair to save and retrieve data.

 

Save Data

First of all we have to get SharedPreferences instance by calling getSharedPreferences() method. It can be done in following way.

1SharedPreferences sp = getSharedPreferences(YourPreferencesKey,Mode);

 

Here first parameter is the user define key in string format and second parameter is the mode. The various modes that we can use are:

MODE_APPENDMODE_ENABLE_WRITE_AHEAD_LOGGINGMODE_MULTI_PROCESSMODE_PRIVATEMODE_WORLD_READABLEMODE_WORLD_WRITEABLE

 

Next step is to get SharedPreferences.Editor class object by calling edit() method using SharedPreferences object. It can be done in following way.

1SharedPreferences.Editor editor = sp.edit();

 

After that call putString() method using Editor object.

1editor.putString(key,value);

 

Here both key and value are in string format. There are some other methods like putBoolean(), putInt(), putLong() and putFloat() to save boolean, integer, long and float values respectively.

 

Finally call commit() method to save the changes.

1editor.commit();

 

Retrieve Data

First get instance of SharedPreferences by calling getSharedPreferences() method. After that use getString() method to fetch the data. It can be done in following way.

12SharedPreferences sp = getSharedPreferences(YourPreferencesKey,Mode);sp.getString(key,default_value);

 

When there is no data associated with given key then the default value is returned. There are some other methods to fetch data, like getBoolean(), getInt(), getFloat() and getLong().

 

We can use contains() method to check whether SharedPreferences contain some value or not.

12345if(sp.contains(key)) { //perform some task here }

 

Modify Data

To modify any data, save the data using the same key that you used earlier. It will overwrite new data on previous data.

 

Delete Data

Use remove() method to delete a data associated with particular key. You can use clear() method to delete all the data present in SharedPreferences. It can be done in following way.

123editor.remove(key); //remove single dataeditor.clear(); //remove all dataeditor.commit();

 

You must always call commit() method after doing any changes in data.

 

Below I have shared one simple example that will show how SharedPreferences is used in android.

 

Android SharedPreferences Example

Create a project with package name thecrazyprogrammer.androidexample. Now paste following code in respective files.

activity_main.xml

1234567891011121314151617181920212223242526272829                

 

MainActivity.java

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748package thecrazyprogrammer.androidexample; import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; public class MainActivity extends Activity {    Button saveButton,removeButton;    EditText text;    SharedPreferences sp;    SharedPreferences.Editor editor;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);         saveButton=(Button)findViewById(R.id.saveButton);        removeButton=(Button)findViewById(R.id.removeButton);        text=(EditText)findViewById(R.id.text);         sp=getSharedPreferences("TheCrazyProgrammer",MODE_PRIVATE);        editor=sp.edit();         if(sp.contains("name")){            text.setText(sp.getString("name","null"));        }    }     public void buttonAction(View view) {         if(view.getId()==R.id.saveButton){            editor.putString("name",text.getText().toString());            editor.commit();            Toast.makeText(getApplicationContext(),"Preferences Saved",Toast.LENGTH_LONG).show();        }         if(view.getId()==R.id.removeButton){            editor.clear();            editor.commit();            Toast.makeText(getApplicationContext(),"Preferences Removed",Toast.LENGTH_LONG).show();        }    }}

 

Run project and save some data using textbox and save button. Now close the application and run it again. You will see that the textbox display the data you have saved earlier. This proves that data is not lost even after closing the application. You can use remove button to delete the data.

Android SharedPreferences Example

 

Comment below if you have any doubts regarding above android SharedPreferences example.

Happy Coding!! 🙂 🙂

You May Also Like:Introduction to Python ProgrammingDifferent Types of Attributes in DBMSC++ Program to print given series:1 2 4 8 16 32 64 128iOS Data Recovery Made Easy with iSkysoft Toolbox: Recover Lost Data in SecondsC++ program to swap two numbers without using temp variable


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有